package com.example.demomk.Adapter;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.demomk.databinding.ItemDetailsBinding;
import com.example.demomk.databinding.ItemEmptyStateBinding;
import com.example.demomk.databinding.ItemHeaderBinding;
import com.example.demomk.entity.AvgMeasurementWithMeasurements;
import com.example.demomk.entity.Measurement;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RuleAdapter extends RecyclerView.Adapter<RuleAdapter.ViewHolder> {
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;
    private static final int TYPE_EMPTY = 2;

    private List<AvgMeasurementWithMeasurements> originalData = new ArrayList<>();
    private Map<Integer, List<Measurement>> measurementsMap = new HashMap<>();
    private List<Boolean> selectedItems = new ArrayList<>();
    public interface  OnItemSelectedListener {
        void onItemSelected(int position, boolean isChecked);
    }
    private OnItemSelectedListener listener;

    public void setOnItemSelectedListener (OnItemSelectedListener listener){
        this.listener = listener;
    }

    public void setData(List<AvgMeasurementWithMeasurements> data, Map<Integer, List<Measurement>> measurements) {
        if (data != null && measurements != null) {
            this.originalData = data;
            this.measurementsMap = new HashMap<>(measurements);
            int totalCount = getItemCount(); // ✅ 使用当前 item 数量
            selectedItems.clear();
            selectedItems.addAll(Collections.nCopies(totalCount, false));
        } else {
            this.originalData.clear();
            this.measurementsMap.clear();
            this.selectedItems.clear();
        }
        notifyDataSetChanged();
    }
    @Override
    public int getItemViewType(int position) {

        // 计算当前位置属于哪个组
//        int groupIndex = 0;
        int itemCount = 0;

        for (AvgMeasurementWithMeasurements group : originalData) {
            // 表头位置
            if (position == itemCount) {
                return TYPE_HEADER;
            }
            itemCount++;

            // 详情项位置
            List<Measurement> measurements = measurementsMap.get(group.avgMeasurement.getId());
            int detailCount = measurements != null ? measurements.size() : 0;

            if (detailCount == 0) {
                // 空状态位置
                if (position == itemCount) {
                    return TYPE_EMPTY;
                }
                itemCount++;
            } else {
                if (position < itemCount + detailCount) {
                    return TYPE_ITEM;
                }
                itemCount += detailCount;
            }

//            groupIndex++;
        }

        throw new IllegalArgumentException("Invalid position");
    }

    @NonNull
    @Override
    public RuleAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_HEADER:
                return new HeaderViewHolder(ItemHeaderBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
            case TYPE_ITEM:
                return new DetailViewHolder(ItemDetailsBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
            case TYPE_EMPTY:
                return new EmptyViewHolder(ItemEmptyStateBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
            default:
                throw new IllegalArgumentException("Invalid view type");
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RuleAdapter.ViewHolder holder, int position) {
        boolean isSelected = position < selectedItems.size() && selectedItems.get(position);

        int itemCount = 0;
        for (AvgMeasurementWithMeasurements group : originalData) {
            if (position == itemCount) {
                ((HeaderViewHolder) holder).bind(group, isSelected, position);
                return;
            }
            itemCount++;

            List<Measurement> measurements = measurementsMap.get(group.avgMeasurement.getId());
            int detailCount = measurements != null ? measurements.size() : 0;

            if (detailCount == 0) {
                if (position == itemCount) {
                    ((EmptyViewHolder) holder).bind(new EmptyState());
                    return;
                }
                itemCount++;
            } else {
                if (position < itemCount + detailCount) {
                    ((DetailViewHolder) holder).bind(measurements.get(position - itemCount));
                    return;
                }
                itemCount += detailCount;
            }
        }

    }

    @Override
    public int getItemCount() {
        int count = 0;
        for (AvgMeasurementWithMeasurements group : originalData) {
            count++; // 表头

            List<Measurement> measurements = measurementsMap.get(group.avgMeasurement.getId());
            if (measurements == null || measurements.isEmpty()) {
                count++; // 空状态
            } else {
                count += measurements.size(); // 详情项
            }
        }
        return count;
    }
    public abstract class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    public class HeaderViewHolder extends ViewHolder {
        TextView id, user_name, location_name, group_name, start_time, flow;
        CheckBox selectAll;
        public HeaderViewHolder(@NonNull ItemHeaderBinding binding) {
            super(binding.getRoot());
            selectAll = binding.userSelect;
            id = binding.ruleId;
            user_name = binding.ruleName;
            location_name = binding.ruleLocation;
            group_name = binding.ruleGroup;
            start_time = binding.ruleTime;
            flow = binding.ruleFlow;
        }
        void bind(AvgMeasurementWithMeasurements group,boolean isSelected,int position) {

            id.setText(String.valueOf(group.avgMeasurement.getId()));
            user_name.setText(group.user.getName());
            location_name.setText(group.location.getName());
            group_name.setText(group.location.getGroup());
            start_time.setText(group.avgMeasurement.getStartTime().split(" ")[0]);
            flow.setText(String.valueOf(group.avgMeasurement.getFlow()) + "LPM");

            // 避免重复设置监听器
            selectAll.setOnCheckedChangeListener(null); // 先移除旧监听器
            selectAll.setChecked(isSelected);
            // 重新设置监听器
            selectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (position < selectedItems.size()) {
                    selectedItems.set(position, isChecked);
                }

                if (listener != null) {
                    listener.onItemSelected(position, isChecked);
                }
            });
        }
    }
    public void selectAll(boolean isChecked) {
        selectedItems.clear();

        // 遍历所有 item 位置
        for (int i = 0; i < getItemCount(); i++) {
            // 只选中头部项（TYPE_HEADER）
            selectedItems.add(getItemViewType(i) == TYPE_HEADER && isChecked);
        }

        notifyDataSetChanged();
    }
    public boolean areAllHeadersSelected() {
        for (int i = 0; i < getItemCount(); i++) {
            if (getItemViewType(i) == TYPE_HEADER) {
                if (i >= selectedItems.size() || !selectedItems.get(i)) {
                    return false;
                }
            }
        }
        return true;
    }
    public class DetailViewHolder extends ViewHolder {
        TextView id , avg_note, start_time , avg_zero , avg_one,  avg_two,avg_there,avg_five, avg_ten,avg_flow;
        public DetailViewHolder(@NonNull ItemDetailsBinding binding) {
            super(binding.getRoot());
            id = binding.avgId;
            avg_note = binding.avgNote;
            start_time = binding.avgStartTime;
            avg_zero = binding.avgZero;
            avg_one = binding.avgOne;
            avg_two = binding.avgTwo;
            avg_there = binding.avgThere;
            avg_five = binding.avgFive;
            avg_ten = binding.avgTen;
            avg_flow = binding.avgFlow;
        }
        void bind(Measurement item) {
            id.setText(String.valueOf(item.getId()));
            start_time.setText(item.getStartTime());
            avg_zero.setText(String.valueOf(item.getValue05()));
            avg_one.setText(String.valueOf(item.getValue10()));
            avg_two.setText(String.valueOf(item.getValue20()));
            avg_there.setText(String.valueOf(item.getValue30()));
            avg_flow.setText(String.valueOf(item.getFlowRate()));
            avg_five.setText(String.valueOf(item.getValue50()));
            avg_ten.setText(String.valueOf(item.getValue100()));
            avg_note.setText(item.getNotes());
        }
    }

    public class EmptyViewHolder extends ViewHolder {
        TextView  emptyText;
        public EmptyViewHolder(@NonNull ItemEmptyStateBinding binding) {
            super(binding.getRoot());
            emptyText  = binding.tvMessage;
        }
        void bind(EmptyState empty) {
            emptyText.setText("暂无测量数据");
        }
    }
    public List<Boolean> getSelectedItems() {
        return selectedItems;
    }
    static class EmptyState {}

}
